#import "NSDateExtension.h"

@implementation NSDate(ForJSON)

+ (NSDate*) getDateFromJSON:(NSString *)dateString
{
    // Expect date in this format "/Date(1268123281843)/"
    int startPos = [dateString rangeOfString:@"("].location+1;
    int endPos = [dateString rangeOfString:@")"].location;
    NSRange range = NSMakeRange(startPos,endPos-startPos);
    unsigned long long milliseconds = [[dateString substringWithRange:range] longLongValue];
    NSLog(@"%llu",milliseconds);
    NSTimeInterval interval = milliseconds/1000;
    return [NSDate dateWithTimeIntervalSince1970:interval];
}

- (NSString*) getJSONDateString
{
	NSTimeInterval millisecondedDate = ([self timeIntervalSince1970] * 1000);
	NSString* formattedMilliseconds = [NSString stringWithFormat:@"%.0f", millisecondedDate];
	NSString *startOfDateFormat = @"/Date(";
	NSString *endOfDateFormat = @"+0400)/";
	NSString *dateTimeNow = [NSString stringWithFormat:@"%@%@%@",startOfDateFormat, formattedMilliseconds, endOfDateFormat];
	return dateTimeNow;
}

+ (NSDate*) dateFrom:(NSArray*)dateInfo
{
	NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
	if (dateInfo.count>=1) {
		[dateComponents setDay:[[dateInfo objectAtIndex:0] intValue]];
	}
	if (dateInfo.count>=2) {
		[dateComponents setMonth:[[dateInfo objectAtIndex:1] intValue]];
	}
	if (dateInfo.count>=3) {
		[dateComponents setYear:[[dateInfo objectAtIndex:2] intValue]];
	}
	if (dateInfo.count>=4) {
		[dateComponents setHour:[[dateInfo objectAtIndex:3] intValue]];
	}
	if (dateInfo.count>=5) {
		[dateComponents setMinute:[[dateInfo objectAtIndex:4] intValue]];
	}
	if (dateInfo.count>=6) {
		[dateComponents setSecond:[[dateInfo objectAtIndex:5] intValue]];
	}
	NSCalendar *calendar = [NSCalendar currentCalendar];
	NSDate *date = [calendar dateFromComponents:dateComponents];
	NSLog(@"test:%@",date);
	[dateComponents release];
	return date;
}

@end
